<template>
	<el-card class="layout-query">
		<el-form ref="queryRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item label="关键词" prop="keyword">
				<el-input v-model="state.keyword" placeholder="请输入" clearable>
					<template #prepend>
						<el-select v-model="state.keyType" placeholder="请选择" style="width: 100px; min-width: 100px" clearable>
							<el-option label="标准编号" value="1" />
							<el-option label="标准名称" value="2" />
							<el-option label="项目负责人" value="3" />
							<el-option label="联系人" value="4" />
						</el-select>
					</template>
				</el-input>
			</el-form-item>
			<el-form-item label="年度" prop="keyword">
				<el-date-picker v-model="state.queryForm.applyYear" type="year" format="YYYY" value-format="YYYY" placeholder="请选择" clearable />
			</el-form-item>
			<el-form-item label="复审来源" prop="souce">
				<el-select v-model="state.queryForm.reviewAddtype" placeholder="请选择" style="width: 100%" clearable>
					<el-option label="系统生成" value="1"></el-option>
					<el-option label="手动添加" value="0"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button icon="Search" type="primary" @click="search()">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button icon="RefreshRight" @click="reset()">重置</el-button>
			</el-form-item>
		</el-form>
	</el-card>
	<el-card>
		<el-form :inline="true" style="text-align: right" class="anniu">
			<el-form-item v-auth="'M003_2_List'">
				<el-button type="primary" @click="createList()">系统生成清单</el-button>
			</el-form-item>
			<el-form-item v-auth="'M003_2_ListExport'">
				<el-button type="primary" @click="exportHandle()">清单导出ecxcel</el-button>
			</el-form-item>
			<el-form-item v-auth="'M003_2_ManualAdd'">
				<el-button type="primary" @click="addOrUpdateHandle()">手动添加复审</el-button>
			</el-form-item>
		</el-form>
		<el-table ref="multipleTableRef" v-loading="state.dataListLoading" :data="dataList" stripe border @selection-change="selectionChangeHandle">
			<el-table-column type="index" label="序号" header-align="center" align="center" width="60"></el-table-column>
			<el-table-column
				prop="implementationTime"
				label="实施日期"
				header-align="center"
				align="center"
				width="120"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="standardNumber" label="标准编号" header-align="center" align="center" width="140" resizable sortable></el-table-column>
			<el-table-column
				prop="standardProjectName"
				label="标准名称"
				header-align="center"
				align="center"
				width="140"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="contactName" label="联系人" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="contactTel" label="联系电话" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="contactEmail" label="联系邮箱" header-align="center" align="center" width="130" resizable sortable></el-table-column>
			<el-table-column prop="projectLeader" label="项目负责人" header-align="center" align="center" width="120" resizable sortable></el-table-column>
			<el-table-column prop="editorUnitName" label="主编单位" header-align="center" align="center" width="150" resizable sortable></el-table-column>
			<el-table-column prop="reviewAddtype" label="复审来源" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span>{{ scope.row.reviewType == 0 ? '系统生成' : '手动添加' }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="reviewStage" label="复审阶段" header-align="center" align="center" width="120" resizable sortable>
				<template #default="scope">
					<span v-if="scope.row.reviewStage">{{ reviewStage.filter(item => item.code === scope.row.reviewStage)[0].name }}</span>
					<!-- <span v-if="scope.row.reviewStage == 4">审核完毕</span> -->
				</template>
			</el-table-column>
			<el-table-column
				prop="reviewStarttime"
				label="复审开始日期"
				header-align="center"
				align="center"
				width="120"
				resizable
				sortable
			></el-table-column>
			<el-table-column
				prop="reviewDeadline"
				label="复审结束日期"
				header-align="center"
				align="center"
				width="120"
				resizable
				sortable
			></el-table-column>
			<el-table-column prop="remark" label="复审结论" header-align="center" align="center" min-width="200">
				<template #default="scope">
					<span v-if="scope.row.remark">{{ reviewResult.filter(item => item.code === scope.row.remark)[0].name }}</span>
					<!-- <span>{{ scope.row.remark }}</span> -->
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="90">
				<template #default="scope">
					<el-icon :size="16" color="#1491FF" title="查看" style="cursor: pointer; margin: 0 6px" @click="detailHandle(scope.row)">
						<View />
					</el-icon>
					<el-icon
						v-auth="'M003_2_Remove'"
						:size="16"
						color="#1491FF"
						title="从清单去除"
						style="cursor: pointer; margin: 0 6px"
						@click="deleteHandle(scope.row)"
					>
						<CircleClose />
					</el-icon>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.pageNum"
			:page-size="state.pageSize"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<addDialog
			v-model="showAddDialog"
			:edit-id="editId"
			:is-view="isView"
			:info="standardInfo"
			:is-audit="true"
			:is-admin="true"
			@submit-success="addSuccess"
		></addDialog>
		<cmDialog v-model="showCreateDialog" modal-title="系统生成清单" model-width="500px">
			<el-form>
				<el-form-item label="复审年度" label-width="100px">
					<el-date-picker v-model="createYear" type="year" format="YYYY" value-format="YYYY" placeholder="请选择" @change="createYearChange" />
				</el-form-item>
			</el-form>
			<div v-if="checkCount > 0" class="tip">
				<el-icon size="18"><WarningFilled /></el-icon>
				<span>已有选定年度的复审清单，确定要重新生成吗？</span>
			</div>
			<div class="dialog-foot">
				<el-button @click="showCreateDialog = false">取消</el-button>
				<el-button type="primary" @click="createSubmit">确定</el-button>
			</div>
		</cmDialog>
	</el-card>
</template>
<script setup lang="ts">
import { reviewDelete } from '@/api/fushen/declare'
import { createInventoryList, getList } from '@/api/fushen/inventory'
import cmDialog from '@/components/cm-dialog/index.vue'
import { StandardInfo } from '@/interface/review'
import { useDictionaryStore } from '@/store/modules/dictionary'
import { useUserStore } from '@/store/modules/user'
import axios from 'axios'
import type { TableInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
import addDialog from '../components/addDialog.vue'

const userStore = useUserStore()
const dictionaryStore = useDictionaryStore()
const reviewStatus = dictionaryStore.getDictionaryByCode('T015')
const reviewResult = dictionaryStore.getDictionaryByCode('T016')
const reviewStage = dictionaryStore.getDictionaryByCode('T0026')

const handleResult = [
	{
		label: '拟继续有效三年',
		value: '1'
	},
	{
		label: '拟暂定有效一年',
		value: '2'
	},
	{
		label: '拟应予修订',
		value: '3'
	},
	{
		label: '拟废除',
		value: '4'
	}
]
const state = reactive({
	queryForm: {
		standardNumber: '',
		standardProjectName: '',
		responsiblePerson: '',
		contactName: '',
		applyYear: '',
		reviewAddtype: '',
		reviewYear: '',
		userName: ''
	},
	pageNum: 1,
	pageSize: 10,
	total: 0,
	dataListLoading: false,
	keyType: '',
	keyword: null
})
const multipleTableRef = ref<TableInstance>()
const dataList = ref([])
const showAddDialog = ref<boolean>(false)
const editId = ref<string>('')
const isView = ref<boolean>(false)
const standardInfo = ref<StandardInfo | null>(null)
const showCreateDialog = ref<boolean>(false)
const createYear = ref<string>('')
const checkCount = ref<number>(0)

watch(
	() => showAddDialog.value,
	newVal => {
		if (!newVal) {
			standardInfo.value = null
			editId.value = ''
			isView.value = false
		}
	}
)

watch(
	() => showCreateDialog.value,
	newVal => {
		if (!newVal) {
			createYear.value = ''
			checkCount.value = 0
		}
	}
)

const getDataList = () => {
	state.queryForm.standardNumber = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.contactName = ''
	if (state.keyword && !state.keyType) {
		ElMessage.error('请选择关键词类型')
		return
	}
	switch (state.keyType) {
		case '1':
			state.queryForm.standardNumber = state.keyword
			break
		case '2':
			state.queryForm.standardProjectName = state.keyword
			break
		case '3':
			state.queryForm.responsiblePerson = state.keyword
			break
		case '4':
			state.queryForm.contactName = state.keyword
			break
	}
	state.dataListLoading = true
	getList({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		const list = res.data.list
		state.dataListLoading = false
		dataList.value = []
		if (list.length > 0) {
			list.forEach((item, index) => {
				dataList.value.push({
					index: index + 1,
					...item
				})
			})
		}
		state.total = res.data.total || 0
	})
}

const search = () => {
	state.pageNum = 1
	getDataList()
}

const reset = () => {
	state.queryForm.standardNumber = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.contactName = ''
	state.queryForm.userName = ''
	state.queryForm.applyYear = ''
	state.queryForm.reviewAddtype = ''
	state.queryForm.reviewYear = ''
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	getDataList()
}

const addOrUpdateHandle = () => {
	showAddDialog.value = true
	isView.value = false
}
const createList = () => {
	showCreateDialog.value = true
}
const createSubmit = () => {
	if (createYear.value === '') {
		ElMessage.error('请选择复审年度')
		return
	}
	state.queryForm.applyYear = ''
	createInventoryList({
		applyYear: createYear.value
	}).then(res => {
		ElMessage.success('生成成功')
		showCreateDialog.value = false
		reset()
	})
}
const selectionChangeHandle = () => {}

const createYearChange = (e: string) => {
	state.queryForm.standardNumber = ''
	state.queryForm.standardProjectName = ''
	state.queryForm.responsiblePerson = ''
	state.queryForm.contactName = ''
	state.queryForm.userName = ''
	state.queryForm.applyYear = e
	state.queryForm.reviewAddtype = ''
	state.queryForm.reviewYear = ''
	state.keyword = null
	state.keyType = ''
	state.pageNum = 1
	checkCount.value = 0
	getList({
		pageIndex: state.pageNum,
		pageSize: state.pageSize,
		...state.queryForm
	}).then(res => {
		checkCount.value = res.data.total || 0
	})
}

const sizeChangeHandle = (e: number) => {
	state.pageSize = e
	state.pageNum = 1
	getDataList()
}
const currentChangeHandle = (e: number) => {
	state.pageNum = e
	getDataList()
}

const detailHandle = (row: any) => {
	standardInfo.value = row
	editId.value = row.id
	showAddDialog.value = true
	isView.value = true
}

const editHandle = (row: any) => {
	standardInfo.value = row
	editId.value = row.id
	showAddDialog.value = true
	isView.value = false
}

const exportHandle = () => {
	try {
		// const selectedRows = multipleTableRef.value.getSelectionRows()
		// if (selectedRows.length == 0) {
		// 	throw new Error('请选择一个项目')
		// }
		// const ids = selectedRows.map(item => {
		// 	return item.id
		// })
		const param = {
			// processor: '',
			// projectId: ids.toString(),
			...state.queryForm
		}
		axios({
			method: 'post',
			url: window.location.protocol + '//' + window.location.host + '/JGBStandardWebApi' + '/api/review/exportInventory',
			headers: {
				'Content-Type': 'application/json;charset=UTF-8',
				Authorization: userStore.token
			},
			data: param,
			responseType: 'blob'
		})
			.then(response => {
				ElMessage.success('操作成功，文件已开始下载')
				const blob = new Blob([response.data], {
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
				})
				const url = window.URL.createObjectURL(blob)
				const a = document.createElement('a')
				a.href = url
				a.download = '复审年度清单导出文件.xls'
				a.click()
				window.URL.revokeObjectURL(url)
			})
			.catch(error => {
				console.error('导出失败:', error)
			})
	} catch (error) {
		console.error('提交处理失败:', error.message)
		ElMessage.error(error.message)
	}
}

const addSuccess = (e: any) => {
	editId.value = ''
	showAddDialog.value = false
	reset()
}

const deleteHandle = (row: any) => {
	ElMessageBox.confirm('确定删除该条数据?', '提示', {}).then(() => {
		reviewDelete({
			id: row.id
		}).then(() => {
			ElMessage.success('删除成功')
			getDataList()
		})
	})
}
onMounted(() => {
	getDataList()
})
</script>
<style lang="scss" scoped>
.anniu .el-form-item {
	margin-right: 10px !important;
}

.dialog-foot {
	display: flex;
	justify-content: center;
	padding-top: 20px;
	margin-bottom: 10px;
}

.tip {
	color: #f00;
	display: flex;
	align-items: center;
	padding-left: 100px;

	span {
		margin-left: 5px;
	}
}
</style>
